package com.ry.novel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ry.novel.bean.UserHolder;
import com.ry.novel.enums.NovelConst;
import com.ry.novel.mapper.BookCommentMapper;
import com.ry.novel.model.dto.BookCommentInfo;
import com.ry.novel.model.dto.UserInfo;
import com.ry.novel.model.dto.condition.CommentQuery;
import com.ry.novel.model.entity.BookComment;
import com.ry.novel.service.BookCommentService;
import com.ry.novel.service.UserService;
import com.ry.novel.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ry
 * @since 2022-02-27 15:03
 **/
@Service
public class BookCommentServiceImpl implements BookCommentService {

    @Autowired
    private BookCommentMapper bookCommentMapper;

    @Autowired
    private UserService userService;


    @Override
    public void addCommment(BookCommentInfo commentInfo) {
        BookComment bookComment = new BookComment();
        bookComment.setBookId(commentInfo.getBookId());
        bookComment.setContent(commentInfo.getContent());
        bookComment.setCreateTime(LocalDateTime.now().toString());
        bookComment.setUserId(UserHolder.userInfo.get().getId());

        //...todo可能以后会加评论审核的功能吧
        bookComment.setState(NovelConst.Comment_PASSED);


        bookCommentMapper.insert(bookComment);
    }

    @Override
    public Page<BookCommentInfo> queryByBookId(CommentQuery commentQuery) {
        Page<BookComment> page = new Page<>(commentQuery.getPage(),commentQuery.getSize());
        Page<BookCommentInfo> infoPage = new Page<>(commentQuery.getPage(),commentQuery.getSize());
        QueryWrapper<BookComment> wrapper = new QueryWrapper<>();
        wrapper.eq("book_id",commentQuery.getBookId());

        bookCommentMapper.selectPage(page, wrapper);

        List<BookCommentInfo> infos = page.getRecords().stream().map(entity -> {
            BookCommentInfo info = new BookCommentInfo();
            info.setId(entity.getId());
            info.setBookId(entity.getBookId());
            info.setContent(entity.getContent());
            info.setCreateTime(DateUtil.format(entity.getCreateTime()));
            info.setUserId(entity.getUserId());
            info.setState(entity.getState());

            UserInfo userInfo = userService.queryUserById(entity.getUserId());
            info.setUsername(userInfo.getUsername());
            info.setUser_photo(userInfo.getUserPhoto());


            return info;
        }).collect(Collectors.toList());

        infoPage.setRecords(infos);
        infoPage.setTotal(page.getTotal());

        return infoPage;
    }
}
